<template>
  <view class="evaluation-container">
    <!-- 顶部标题栏 -->
    <view class="page-header">
      <view class="header-title">订单评价</view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="order-header">
        <view class="order-number">
          <text class="number-label">订单编号：</text>
          <text>{{ orderInfo.id }}</text>
        </view>
        <view class="order-status" :class="`status-${getStatusClass(orderInfo.status)}`">
          {{ getStatusText(orderInfo.status) }}
        </view>
      </view>

      <view class="order-details">
        <view class="detail-row">
          <text class="detail-icon">🔧</text>
          <text class="detail-label">服务类型</text>
          <text class="detail-value">{{ orderInfo.type }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-icon">📍</text>
          <text class="detail-label">服务地址</text>
          <text class="detail-value">{{ orderInfo.address }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-icon">👤</text>
          <text class="detail-label">客户姓名</text>
          <text class="detail-value">{{ orderInfo.customerName }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-icon">📱</text>
          <text class="detail-label">联系电话</text>
          <text class="detail-value">{{ orderInfo.customerPhone }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-icon">👨‍🔧</text>
          <text class="detail-label">接单师傅</text>
          <text class="detail-value">{{ orderInfo.masterName || '暂无' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-icon">⏰</text>
          <text class="detail-label">服务时间</text>
          <text class="detail-value">{{ orderInfo.time }}</text>
        </view>
        <view class="detail-row price-row">
          <text class="detail-icon">💴</text>
          <text class="detail-label">服务报酬</text>
          <text class="detail-value" v-if="orderInfo.status === 2">¥{{ (parseFloat(orderInfo.price || 0) + parseFloat(orderInfo.servicePay || 0)).toFixed(2) }}</text>
          <text class="detail-value" v-else-if="orderInfo.status === 0 || orderInfo.status === 1">等待员工结算</text>
          <text class="detail-value" v-else>¥{{ orderInfo.price?.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 评分区域 -->
    <view class="rating-section">
      <view class="section-title">服务评分</view>
      <view class="rating-stars">
        <view 
          class="star" 
          v-for="(star, index) in 5" 
          :key="index"
          @click="setRating(index + 1)"
        >
          <text class="star-icon" :class="{ 'active': rating > index }">
            {{ rating > index ? '★' : '☆' }}
          </text>
        </view>
        <text class="rating-text">{{ getRatingText(rating) }}</text>
      </view>
    </view>

    <!-- 评价内容 -->
    <view class="comment-section">
      <view class="section-title">评价内容</view>
      <textarea 
        class="comment-textarea" 
        placeholder="请描述您的服务体验..."
        v-model="comment"
        maxlength="200"
      />
      <view class="word-count">{{ comment.length }}/200</view>
    </view>


    <!-- 提交按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submitEvaluation">提交评价</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getWorkOrderDetailAPI, submitWorkOrderEvaluation } from '@/api/order.js'
import { getUserInfoAPI } from '@/api/sys.js'

// 订单信息
const orderInfo = ref({
  id: '',
  type: '',
  address: '',
  time: '',
  price: 0,
  status: '',
  customerName: '',
  customerPhone: ''
})

// 评分（1-5星）
const rating = ref(0)

// 评价内容
const comment = ref('')

// 获取评分文本
const getRatingText = (rating) => {
  const texts = {
    0: '未评分',
    1: '非常不满意',
    2: '不满意',
    3: '一般',
    4: '满意',
    5: '非常满意'
  }
  return texts[rating] || ''
}

// 设置评分
const setRating = (value) => {
  rating.value = value
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '待分配',
    1: '处理中',
    2: '已完成',
    3: '已取消',
    4: '已评价'
  }
  return map[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const map = {
    0: 'pending',
    1: 'appointment',
    2: 'completed',
    3: 'canceled',
    4: 'commented'
  }
  return map[status] || 'pending'
}

// 提交评价
const submitEvaluation = async () => {
  if (rating.value === 0) {
    uni.showToast({
      title: '请先评分',
      icon: 'none'
    })
    return
  }

  uni.showLoading({
    title: '提交中...'
  })

  try {
    // 获取当前用户信息
    const userInfo = uni.getStorageSync('userInfo')
    
    // 构造评价数据
    const evaluationData = {
      workOrderId: orderInfo.value.id,        // 工单ID
      starRating: rating.value,               // 评分
      content: comment.value || '',           // 评价内容
      customerId: userInfo?.id || '',         // 客户ID（评价者）
      userId: orderInfo.value.employeeId || '' // 员工ID（被评价者）
    }

    // 调用API提交评价
    
    // 检查所有必要字段是否存在
    if (!evaluationData.workOrderId) {
      uni.showToast({
        title: '工单ID缺失，无法提交评价',
        icon: 'none'
      });
      uni.hideLoading();
      return;
    }
    
    // 客户ID（应该引用customer_info表）
    if (!evaluationData.customerId) {
      uni.showToast({
        title: '客户ID缺失，无法提交评价',
        icon: 'none'
      });
      uni.hideLoading();
      return;
    }
    
    // 员工ID（应该引用sys_user表）
    if (!evaluationData.userId) {
      uni.showToast({
        title: '员工ID缺失，无法提交评价',
        icon: 'none'
      });
      uni.hideLoading();
      return;
    }
    
    const result = await submitWorkOrderEvaluation(evaluationData)
    
    if (result.success) {
      uni.showToast({
        title: '评价提交成功',
        icon: 'success'
      })
      
      // 更新订单状态为已评价(状态码4)
      orderInfo.value.status = 4
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: result.message,
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交评价失败:', error)
    uni.showToast({
      title: '评价提交失败: ' + (error.message || '未知错误'),
      icon: 'none'
    })
  } finally {
    // 确保总是隐藏loading
    uni.hideLoading()
  }
}

// 页面加载时获取订单信息
onLoad(async (options) => {
  const orderId = options?.id || options?.query?.id
  if (orderId) {
    uni.showLoading({ title: '加载中...' })
    
    try {
      // 调用API获取订单详情
      const result = await getWorkOrderDetailAPI(orderId)
      
      // 检查API响应格式，确保请求成功
      if (result && result.code === 0 && result.data) {
        const data = result.data
        
        // 如果有employeeName/masterName/employee但没有employeeId，则调用接口获取员工信息
        let employeeName = data.employeeName || data.masterName || data.employee || '';
        if (!employeeName && data.employeeId) {
          const employeeInfo = await getUserInfoAPI(data.employeeId);
          if (employeeInfo) {
            // 修复字段名，后端返回的是userName字段
            employeeName = employeeInfo.userName || employeeInfo.name || employeeInfo.username || '';
          }
        }
        
        // 根据工单系统数据映射规范映射字段
        orderInfo.value = {
          id: data.id || '',
          // title对应工单类型
          type: data.title || '',
          // address对应服务地址
          address: data.address || '',
          // 使用创建时间或更新时间作为服务时间
          time: data.createTime || data.updateTime || data.appointmentTime || '',
          price: data.price || 0,
          // 状态码映射
          status: data.status !== undefined ? data.status : 0,
          // name对应客户姓名
          customerName: data.name || '',
          // phone对应联系电话
          customerPhone: data.phone || '',
          // employeeId对应接单员工ID，需要获取员工姓名
          employeeId: data.employeeId || '',  // 添加这行来保存员工ID
          masterName: employeeName
        }
      } else {
        console.error('获取订单详情失败，错误码:', result?.code, '错误信息:', result?.msg)
        uni.showToast({
          title: result?.msg || '获取订单信息失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      uni.showToast({
        title: '获取订单信息失败',
        icon: 'none'
      })
    } finally {
      uni.hideLoading()
    }
  } else {
    uni.showToast({
      title: '订单ID无效',
      icon: 'none'
    })
  }
})
</script>

<style scoped>
.evaluation-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-size: 28rpx;
  padding-bottom: 40rpx;
}

.page-header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.header-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.order-info {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 25rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx dashed #eee;
}

.order-number {
  color: #333;
}

.number-label {
  color: #999;
  margin-right: 5rpx;
}

.order-status {
  padding: 5rpx 15rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background-color: #fff7e6;
  color: #ff9a2e;
}

.status-completed {
  background-color: #e6ffed;
  color: #00b42a;
}

.status-appointment {
  background-color: #e8f3ff;
  color: #1890ff;
}

.status-commented {
  background-color: #f0f0f0;
  color: #666;
}

.order-details {
  margin-bottom: 10rpx;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  line-height: 1.5;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-icon {
  margin-right: 15rpx;
  font-size: 28rpx;
  width: 30rpx;
  text-align: center;
}

.detail-label {
  color: #999;
  margin-right: 10rpx;
  width: 120rpx;
}

.detail-value {
  flex: 1;
  color: #666;
  word-break: break-all;
}

.price-row .detail-value {
  color: #ff4d4f;
  font-weight: 500;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin: 20rpx 20rpx 10rpx;
}

.rating-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 25rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.rating-stars {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.star {
  margin-right: 10rpx;
}

.star-icon {
  font-size: 50rpx;
  color: #ccc;
}

.star-icon.active {
  color: #ff9a2e;
}

.rating-text {
  margin-left: 20rpx;
  color: #ff9a2e;
  font-weight: bold;
}

.comment-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 25rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.comment-textarea {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  box-sizing: border-box;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
  margin-top: 10rpx;
}

.word-count {
  text-align: right;
  color: #999;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.anonymous-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 25rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.submit-section {
  padding: 40rpx 20rpx 20rpx;
}

.submit-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1677ff;
  color: #fff;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
}
</style>